package com.ssm.controller;

import com.ssm.entity.User;
import com.ssm.service.UserServiceImpl;
import com.ssm.util.MenuHelper;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.http.HttpSession;

@Controller
public class IndexController {
	@Autowired
	private UserServiceImpl userService;

	@RequestMapping("/")
	public String index(){
		//此处应判断用户是否登录了，如果已登录则跳转到主页，否则跳转到登录页
		return "redirect:/login";
	}
	@RequestMapping("/login")
	public String login(Model model){
		return "login";
	}
	
	@RequestMapping("/register")
	public String register(Model model){
		return "register";
	}
	
	/**
	 * 注册处理 - 为了向后兼容，保留此方法
	 * 但实际上应该使用RESTful API /api/auth/register
	 */
	@RequestMapping("/doregister")
	@ResponseBody
	public Map<String, Object> doRegister(User user){
		Map<String, Object> result = new HashMap<>();
		// 设置默认角色为普通用户（假设角色id为2）
		if (user.getRole() == null) {
			com.ssm.entity.Role role = new com.ssm.entity.Role();
			role.setRid(2); // 假设2是普通用户角色
			user.setRole(role);
		}
		
		// 设置用户状态为正常
		user.setStatus(1);
		
		String registerResult = userService.add(user);
		if (registerResult.contains("\"Status\":\"ok\"")) {
			result.put("Status", "ok");
		} else {
			result.put("Status", "error");
			result.put("msg", registerResult.contains("\"msg\":") ? 
				registerResult.substring(registerResult.indexOf("\"msg\":") + 6, registerResult.indexOf("}", registerResult.indexOf("\"msg\":"))) : 
				"注册失败，可能用户名已存在");
		}
		return result;
	}
	
	@RequestMapping("/dologin")
	@ResponseBody
	public Map<String, Object> dologin(User user, HttpSession session, boolean remember){
		Map<String, Object> result = new HashMap<>();
		
		if(userService.login(user)) {
			// 获取完整的用户信息
			String userJson = userService.get(Integer.parseInt(userService.getUserIdByName(user.getUname())));
			// 解析JSON获取用户对象
			com.alibaba.fastjson.JSONObject userObj = com.alibaba.fastjson.JSON.parseObject(userJson);
			
			// 构建完整的用户对象
			User fullUser = new User();
			fullUser.setUid(userObj.getIntValue("uid"));
			fullUser.setUname(userObj.getString("uname"));
			fullUser.setAlias(userObj.getString("alias"));
			fullUser.setPasswd(userObj.getString("passwd"));
			fullUser.setLogo(userObj.getString("logo"));
			fullUser.setLast_login_time(userObj.getString("last_login_time"));
			fullUser.setStatus(userObj.getIntValue("status"));
			
			// 设置角色
			com.ssm.entity.Role role = new com.ssm.entity.Role();
			role.setRid(userObj.getIntValue("rid"));
			fullUser.setRole(role);
			
			// 将用户信息存入session
			session.setAttribute("loginUser", fullUser);
			
			result.put("Status", "ok");
			result.put("url", "index");
		} else {
			result.put("Status", "error");
			result.put("msg", "用户名或密码错误");
		}
		return result;
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session){
		// 清除session
		session.invalidate();
		return "redirect:/login";
	}
	
	@RequestMapping("/index")
	public String index(Model model, HttpSession session){
		// 检查用户是否登录
		User loginUser = (User) session.getAttribute("loginUser");
		if (loginUser == null) {
			return "redirect:/login";
		}
		
		String path = "classpath:admin_menu.xml";
		String menu = MenuHelper.getMenu(path);
		model.addAttribute("menu", menu);
		model.addAttribute("loginUser", loginUser);
		return "index";
	}
}